using Microsoft.AspNetCore.Mvc;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Bll.Services;

namespace HDLogCenter.Controllers
{
    public class ProjectController : Controller
    {
        private readonly ProjectConfigService _projectConfigService;
        private readonly AlertRuleService _alertRuleService;

        public ProjectController(ProjectConfigService projectConfigService, AlertRuleService alertRuleService)
        {
            _projectConfigService = projectConfigService;
            _alertRuleService = alertRuleService;
        }

        public async Task<IActionResult> Index()
        {
            var projects = await _projectConfigService.GetAllProjectsAsync();
            return View(projects);
        }

        public IActionResult Create()
        {
            return View(new AppConfigModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(AppConfigModel project)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var id = await _projectConfigService.CreateProjectAsync(project);
                    if (id > 0)
                    {
                        return RedirectToAction(nameof(Index));
                    }
                    ModelState.AddModelError("", "创建项目失败");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"创建项目失败: {ex.Message}");
                }
            }
            return View(project);
        }

        public async Task<IActionResult> Edit(long id)
        {
            var project = await _projectConfigService.GetProjectByIdAsync(id);
            if (project == null)
            {
                return NotFound();
            }
            return View(project);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(long id, AppConfigModel project)
        {
            if (id != project.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var result = await _projectConfigService.UpdateProjectAsync(project);
                    if (result)
                    {
                        return RedirectToAction(nameof(Index));
                    }
                    ModelState.AddModelError("", "更新项目失败");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"更新项目失败: {ex.Message}");
                }
            }
            return View(project);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(long id)
        {
            var result = await _projectConfigService.DeleteProjectAsync(id);
            return Json(new { success = result });
        }

        [HttpPost]
        public async Task<IActionResult> UpdateStatus(long id, int status)
        {
            // 这里需要实现更新项目状态的逻辑
            // 暂时返回成功
            return Json(new { success = true });
        }

        // 告警规则管理
        public async Task<IActionResult> AlertRules(long projectId)
        {
            var project = await _projectConfigService.GetProjectByIdAsync(projectId);
            if (project == null)
            {
                return NotFound();
            }

            var alertRules = await _alertRuleService.GetAlertRulesByAppCodeAsync(project.AppCode);
            ViewBag.Project = project;
            return View(alertRules);
        }

        public async Task<IActionResult> CreateAlertRule(long projectId)
        {
            var project = await _projectConfigService.GetProjectByIdAsync(projectId);
            if (project == null)
            {
                return NotFound();
            }

            ViewBag.Project = project;
            return View(new AlertRuleModel { ProjectCode = project.AppCode });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateAlertRule(long projectId, AlertRuleModel alertRule)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var id = await _alertRuleService.CreateAlertRuleAsync(alertRule);
                    if (id > 0)
                    {
                        return RedirectToAction(nameof(AlertRules), new { projectId });
                    }
                    ModelState.AddModelError("", "创建告警规则失败");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"创建告警规则失败: {ex.Message}");
                }
            }

            var project = await _projectConfigService.GetProjectByIdAsync(projectId);
            ViewBag.Project = project;
            return View(alertRule);
        }

        public async Task<IActionResult> EditAlertRule(long projectId, long id)
        {
            var project = await _projectConfigService.GetProjectByIdAsync(projectId);
            if (project == null)
            {
                return NotFound();
            }

            var alertRule = await _alertRuleService.GetAlertRuleByIdAsync(id);
            if (alertRule == null)
            {
                return NotFound();
            }

            ViewBag.Project = project;
            return View(alertRule);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> EditAlertRule(long projectId, long id, AlertRuleModel alertRule)
        {
            if (id != alertRule.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var result = await _alertRuleService.UpdateAlertRuleAsync(alertRule);
                    if (result)
                    {
                        return RedirectToAction(nameof(AlertRules), new { projectId });
                    }
                    ModelState.AddModelError("", "更新告警规则失败");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"更新告警规则失败: {ex.Message}");
                }
            }

            var project = await _projectConfigService.GetProjectByIdAsync(projectId);
            ViewBag.Project = project;
            return View(alertRule);
        }

        [HttpPost]
        public async Task<IActionResult> DeleteAlertRule(long id)
        {
            try
            {
                var result = await _alertRuleService.DeleteAlertRuleAsync(id);
                return Json(new { success = result, message = result ? "删除成功" : "删除失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败: {ex.Message}" });
            }
        }
    }
}
